<?php

namespace App\Service\Admin;

use App\Repositories\Eloquent\UserRepositoryEloquent;
use App\Repositories\Eloquent\RoleRepositoryEloquent;
use App\Repositories\Eloquent\PermissionRepositoryEloquent;
use App\Service\Admin\BaseService;
use Exception;

/**
* 角色service
*/
class UserService extends BaseService
{
    private $user;
    private $role;
    private $permission;

    function __construct(
        UserRepositoryEloquent $user,
        RoleRepositoryEloquent $role,
        PermissionRepositoryEloquent $permission
    )
    {
        $this->user =  $user;
        $this->role =  $role;
        $this->permission =  $permission;
    }

    /**
     * datatables获取数据
     */
    public function ajaxIndex()
    {
        // datatables请求次数
        $draw = request('draw', 1);
        // 开始条数
        $start = request('start', config('admin.golbal.list.start'));
        // 每页显示数目
        $length = request('length', config('admin.golbal.list.length'));
        // datatables是否启用模糊搜索
        $search['regex'] = request('search.regex', false);
        // 搜索框中的值
        $search['value'] = request('search.value', '');
        // 排序
        $order['name'] = request('columns.' .request('order.0.column',0) . '.name');
        $order['dir'] = request('order.0.dir','asc');

        $result = $this->user->getUserList($start,$length,$search,$order);

        $users = [];

        if ($result['users']) {
            foreach ($result['users'] as $v) {
                $v->actionButton = $v->getActionButtonAttribute();
                $users[] = $v;
            }
        }

        return [
            'draw' => $draw,
            'recordsTotal' => $result['count'],
            'recordsFiltered' => $result['count'],
            'data' => $users,
        ];
    }

    /**
     * 创建用户视图数据
     */
    public function createView()
    {
        return [ $this->getAllPermissionList(), $this->getAllRoles() ];
    }

    /**
     * 获取所有权限并分组
     */
    public function getAllPermissionList()
    {
        return $this->permission->groupPermissionList();
    }

    /**
     * 获取所有的角色
     */
    public function getAllRoles()
    {
        return $this->role->all(['id','name']);
    }

    /**
     * 添加用户
     */
    public function storeUser($formData)
    {
        try {
            $result = $this->user->create($formData);
            if ($result) {
                // 角色与用户关系
                if ($formData['role']) {
                    $result->roles()->sync($formData['role']);
                }
                // 权限与用户关系
                if ($formData['permission']) {
                    $result->userPermissions()->sync($formData['permission']);
                }
            }
            flash_info($result,trans('admin/alert.user.create_success'),trans('admin/alert.user.create_error'));
            return $result;
        } catch (Exception $e) {
            // 错误信息发送邮件
            $this->sendSystemErrorMail(env('MAIL_SYSTEMERROR',''),$e);
            return false;
        }
    }

    /**
     * 编辑用户视图所需数据
     */
    public function editView($id)
    {
        return [ $this->findUserById($id), $this->getAllPermissionList(), $this->getAllRoles() ];
    }

    /**
     * 根据ID获取权限数据
     * [查询出来的权限对象，查不到数据时跳转404]
     */
    public function findUserById($id)
    {
        $role = $this->user->with( ['userPermissions', 'roles'] )->find($id);
        if ($role) {
            return $role;
        }
        abort(404);
    }

    /**
     * 修改用户
     * @param  [type]                   $attributes [表单数据]
     * @param  [type]                   $id         [resource路由传递过来的id]
     * @return [type]                               [Boolean]
     */
    public function updateUser($attributes,$id)
    {
        // 防止用户恶意修改表单id，如果id不一致直接跳转500
        if ($attributes['id'] != $id) {
            abort(500,trans('admin/errors.user_error'));
        }
        try {
            $result = $this->user->update($attributes,$id);
            if ($result) {
                // 更新用户角色关系
                if (isset($attributes['role'])) {
                    $result->roles()->sync($attributes['role']);
                }else{
                    $result->roles()->sync([]);
                }
                // 更新用户权限关系
                if (isset($attributes['permission'])) {
                    $result->userPermissions()->sync($attributes['permission']);
                }else{
                    $result->userPermissions()->sync([]);
                }
            }
            flash_info($result,trans('admin/alert.user.edit_success'),trans('admin/alert.user.edit_error'));
            return $result;
        } catch (Exception $e) {
            // 错误信息发送邮件
            $this->sendSystemErrorMail(env('MAIL_SYSTEMERROR',''),$e);
            return false;
        }
    }

    /**
     * 用户暂不做状态管理，直接删除
     */
    public function destroyUser($id)
    {
        try {
            $result = $this->user->delete($id);
            flash_info($result,trans('admin/alert.user.destroy_success'),trans('admin/alert.user.destroy_error'));
            return $result;
        } catch (Exception $e) {
            // 错误信息发送邮件
            $this->sendSystemErrorMail(env('MAIL_SYSTEMERROR',''),$e);
            return false;
        }
    }

    /**
     * 重置用户密码
     */
    public function resetUserPassword($id)
    {
        $responseData = [
            'status'=> false,
            'msg'   => trans('admin/alert.user.reset_error'),
        ];
        $result = $this->user->update(['password' => config('admin.global.reset')],$id);
        if ($result) {
            $responseData['status'] = true;
            $responseData['msg']    = trans('admin/alert.user.reset_success');
        }
        return $responseData;
    }

}